package examples.rrc;

import java.net.*;
import java.io.*;

//import MT.*;

class Train extends TimeThread {
  RRC rrc;
  int delta, gamma, ni, ip;
  float speed; // How many meter train goes per 1 time unit.
  int local_clock = 0, global_clock = 0;

  Train(RRC r) {
    rrc = r;
    delta = r.delta;
    gamma = r.gamma;
    ni = r.ni;
    ip = r.ip;

    time_unit = r.time_unit;
    time_tolerant = r.time_tolerant;

    speed = (float) (rrc.rr_length + rrc.train_length)
        / (float) (ni + ip + delta);
    // System.out.println( speed );
  }

  public void running() {
    // Train position updated 1 time unit
    rrc.train_x += speed;

    rrc.showStatus("Local time : " + local_clock + ", Global time : "
        + global_clock);
    local_clock++;
    global_clock++;

    try {
      Thread.sleep(time_unit - get_calc_time() - time_tolerant);
    } catch (InterruptedException e) {
    } catch (IllegalArgumentException e) {
    }
    set_calc_start();
  }

  void Nc() {
    rrc.showStatus("Near Crossing!!!");
  }

  void Ic() {
    rrc.showStatus("In Crossing!!!");
  }

  void Pc() {
    rrc.showStatus("Passed Crossing!!!");
  }

  void ns() {
    rrc.controller.ns.send();
  }

  void ps() {
    rrc.controller.ps.send();
  }

  private void passTime() {
    // Repeated 1 time unit waiting
    rrc.showStatus("Local time : " + local_clock + ", Global time : "
        + global_clock);
    global_clock++;

    try {
      Thread.sleep(time_unit - get_calc_time() - time_tolerant);
    } catch (InterruptedException e) {
    } catch (IllegalArgumentException e) {
    }
    set_calc_start();
    // if(rrc.use_timed_event) FT.send("{}");
  }

  public void run() {
    set_calc_start();
    while (true) {
      local_clock = 0;
      rrc.train_x = 0 - rrc.train_length;
      passTime();

      while (Math.random() > 0.5) {
        passTime();
      }

      // Train comes near crossing : Nc_bar
      Nc();
      ns();

      // Running ni time_unit
      for (int i = 0; i < ni; i++)
        running();

      // Train comes in crossing
      Ic();

      // Running ip time unit in crossing area
      for (int i = 0; i < ip; i++)
        running();

      // Train passes crossing
      Pc();
      ps();

      // Running delta time unit after crossing
      for (int i = 0; i < delta; i++)
        running();
      set_calc_start();
    }
  }// End of void run()
}// End of Class Train
